
// Connection information
// 193.167.45.140:8888
var address = document.location.hostname; 
var port = document.location.port;
//var address = "193.167.45.140";
//var port = 8888;

var NOT_MOVING = 0;
var MOVING_DRIVE = 1; // forward and backward
var MOVING_TURN = 2; // turning left and right

var CAM_H_LIMIT = 180;
var CAM_H_CENTER = 90;
var CAM_V_LIMIT = 50;
var CAM_V_CENTER = 120;

// constants for reading the spectrometer
var SR = 1;
var SG = 2;
var SB = 3;
var SIR = 4;

var interface_language = 'fi';

// for creating a command stack
function Cmd(m, s, d) {
	this.moving = m;
	this.speed = s;
	this.duration = d;
}

var commands = new Array();

// saving sensor data
var spec_red_counter = 0;
var spec_green_counter = 0;
var spec_blue_counter = 0;
var spec_ir_counter = 0;
var spec_red_tmp = new Array(0,0,0,0,0);
var spec_green_tmp = new Array(0,0,0,0,0);
var spec_blue_tmp = new Array(0,0,0,0,0);
var spec_ir_tmp = new Array(0,0,0,0,0);
var spec_red = new Array(0,0,0,0,0,0,0,0,0,0);
var spec_green = new Array(0,0,0,0,0,0,0,0,0,0);
var spec_blue = new Array(0,0,0,0,0,0,0,0,0,0);
var spec_ir = new Array(0,0,0,0,0,0,0,0,0,0);
var humidity = new Array(0,0,0,0,0,0,0,0,0,0);
var temperature = new Array(0,0,0,0,0,0,0,0,0,0);
var solar = new Array(0,0,0,0,0,0,0,0,0,0);


var rover = {
	control: false,
    moving: NOT_MOVING,
    speed: 0,
    camh: 90,
    camv: 90,
    control_camera: false,
	spec_red: 0,
	spec_green: 0,
	spec_blue: 0,
	spec_ir: 0,
	spec_calibrated: false,
    stop: function() {
        if (this.moving != NOT_MOVING) {
            this.moving = NOT_MOVING;
            this.speed = 0;
            mars.send('send:s');
        }
    },
    setSpeed: function(newspeed) {
        if (newspeed != this.speed) {
            this.speed = newspeed;
            if (newspeed == 0)
                mars.send('send:s');
            else if (this.moving == MOVING_DRIVE && newspeed > 0)
                mars.send('send:e'+newspeed);
            else if (this.moving == MOVING_DRIVE && newspeed < 0)
                mars.send('send:t'+(-newspeed));
            else if (this.moving == MOVING_TURN && newspeed > 0)
                mars.send('send:o'+newspeed);
            else if (this.moving == MOVING_TURN && newspeed < 0)
                mars.send('send:v'+(-newspeed));
        }
    },
    setCameraH: function(angle) {
        console.log('setCameraH('+angle+')');
        angle = Math.round((angle-90)*CAM_H_LIMIT/180+CAM_H_CENTER);
        console.log('  converted to '+angle);
        if (angle != this.camh) {
            this.camh = angle;
            mars.send('send:h'+angle);
        }
    },
    setCameraV: function(angle) {
        console.log('setCameraV('+angle+')');
        angle = Math.round((angle-90)*CAM_V_LIMIT/180+CAM_V_CENTER);
        console.log('  converted to '+angle);
        if (angle != this.camv) {
            this.camv = angle;
            mars.send('send:p'+angle);
        }
    },
    askCameraPosition: function() {
        mars.send('send:!');
    },
    attachCamera: function(setmode) {
        if (setmode !== false)
            this.camera = true;
        mars.send('send:k');
    },
    detachCamera: function() {
        this.camera = false;
        mars.send('send:K');
    },
	getSpectrometerCalibration: function() {
		console.log("asking for spec calibration");
		mars.send('get:spectrometer_calibration');
	},
	measureSpectrum: function() {
		mars.send('send:s');
		mars.send('send:m');
	},
	measureTemperature: function() {
		mars.send('send:s');
		mars.send('send:l');
	},
	measureHumidity: function() {
		mars.send('send:s');
		mars.send('send:f');
	},
};
var mars = {send: function(){}}; // this will become the connection

function create_pad() {
    var min_movement = 0.2; // need to move the knob at least 20%
    var min_turning = 0.45;  // will start turning only at 0.5
    
    var stage = new Kinetic.Stage({
        container: 'control_pad',
        width: 330,
        height: 330
    });
    
    var shapesLayer = new Kinetic.Layer();
    /*
    var text_x = new Kinetic.Text({
        x: 10,
        y: 10,
        text: 'x',
        fontSize: 10,
        fontFamily: 'Calibri',
        textFill: 'black'
    });
    
    var text_y = new Kinetic.Text({
        x: 10,
        y: 30,
        text: 'y',
        fontSize: 10,
        fontFamily: 'Calibri',
        textFill: 'black'
    });
    */
    
    var start_x = stage.getWidth() / 2;
    var start_y = stage.getHeight() / 2;
    var max_turning = stage.getWidth() / 3.0 - 5;
    var max_driving = stage.getHeight() / 3.0 - 5;
    var max_camera = (max_turning + max_driving) / 2;
    
    var horz_line = new Kinetic.Line({
        points: [start_x-max_turning, start_y, start_x+max_turning, start_y],
        stroke: "green",
        strokeWidth: 5,
        lineJoin: "round",
        dashArray: [5, 5]
    });
    
    var vert_line = new Kinetic.Line({
        points: [start_x, start_y-max_driving, start_x, start_y+max_driving],
        stroke: "green",
        strokeWidth: 5,
        lineJoin: "round",
        dashArray: [5, 5]
    });
    
    var camera_circle = new Kinetic.Circle({
        x: start_x,
        y: start_y,
        radius: max_camera+5,
        stroke: 'white',
        strokeWidth: 5,
        lineJoin: "round",
        dashArray: [5, 5]
    });
    
    var inner_circle = new Kinetic.Circle({
        x: start_x,
        y: start_y,
        radius: (start_x+start_y)/8,
        stroke: 'green',
        strokeWidth: 1,
        lineJoin: "round",
        dashArray: [5, 5]
    });
    
    //shapesLayer.add(text_x);
    //shapesLayer.add(text_y);
	
    shapesLayer.add(camera_circle);
    shapesLayer.add(vert_line);
    shapesLayer.add(horz_line);
    //shapesLayer.add(outer_circle);
    shapesLayer.add(inner_circle);
    
    function camera_bound(pos) {
        var x = pos.x;
        var y = pos.y;
        var relx = (x - start_x)/max_camera;
        var rely = (y - start_y)/max_camera;
        var dist = Math.sqrt(Math.pow(relx, 2) + Math.pow(rely, 2));
        if (dist > 1) {
            relx /= dist;
            rely /= dist;
            return {
                x: relx*max_camera+start_x,
                y: rely*max_camera+start_y
            }
        }
        return pos;
    }
    
    function movement_bound(pos) {
        var relx = (pos.x - start_x)/max_turning;
        var rely = (pos.y - start_y)/max_driving;
        if (rover.moving == NOT_MOVING) {
            // check which way the knob is being dragged to choose what to do
            if (Math.abs(relx) > Math.abs(rely)) {
                if (Math.abs(relx) > min_movement) {
                    // turning motion
                    vert_line.setStroke('gray');
                    horz_line.setStroke('red');
                    knob.setFill('red');
                    rover.moving = MOVING_TURN;
                }
                else {
                    // not enough movement
                    return pos;
                }
            }
            else if (Math.abs(rely) > min_movement) {
                // driving motion
                horz_line.setStroke('gray');
                vert_line.setStroke('red');
                knob.setFill('blue');
                rover.moving = MOVING_DRIVE;
            }
            else {
                // not enough movement
                return pos;
            }
        }
        if (rover.moving == MOVING_DRIVE) {
            // constraint movement to y axis
            if (rely > 1.0)
                rely = 1.0;
            else if (rely < -1.0)
                rely = -1.0;
            if (Math.abs(rely) < min_movement) {
                reset_stage();
            }
            relx = 0.0;
        }
        else if (rover.moving == MOVING_TURN) {
            // constraint movement to x axis
            if (relx > 1.0)
                relx = 1.0;
            else if (relx < -1.0)
                relx = -1.0;
            if (Math.abs(relx) < min_movement) {
                reset_stage();
            }
            else if (Math.abs(relx) < min_turning) {
                knob.setFill('red');
            }
            else {
                knob.setFill('blue');
            }
            rely = 0.0;
        }
        return {
            y: Math.round(start_y + rely * max_driving),
            x: Math.round(start_x + relx * max_turning)
        };
    }
    
    var knob = new Kinetic.Circle({
        x: start_x,
        y: start_y,
        radius: (start_x+start_y)/8,
        fill: 'green',
        stroke: 'black',
        strokeWidth: 3,
        draggable: true,
        dragBoundFunc: movement_bound
    });
	
	console.log(knob);
    
    function update_movement() {
        if (rover.camera) {
            rover.setCameraH((start_x-knob.getX())/max_camera*90+90);
            rover.setCameraV((knob.getY()-start_y)/max_camera*90+90);
        }
        else {
            if (rover.moving == MOVING_DRIVE)
                rover.setSpeed(Math.round((start_y-knob.getY())/max_driving*10));
            if (rover.moving == MOVING_TURN) {
                var speed = Math.round((knob.getX()-start_x)/max_turning*10);
                if (Math.abs(speed) < min_turning*10) speed = 1;
                rover.setSpeed(speed);
            }
        }
        stage.draw();
    };
    
    function reset_stage() {
        if (rover.camera) {
        }
        else {
            knob.setX(start_x);
            knob.setY(start_y);
            vert_line.setStroke('green');
            horz_line.setStroke('green');
            knob.setFill('green');
            rover.stop();
            update_movement();
        }
    };
        
    knob.on('dragmove', function() {
        update_movement();
    });
    knob.on('mouseup', function() {
        reset_stage();
    });
    document.getElementById('control_pad').addEventListener('mousedown',
        function(ev) {
            ev.preventDefault();
        }, false);
    document.addEventListener('mouseup', reset_stage, false);
    document.addEventListener('touchend', reset_stage, false);
    shapesLayer.add(knob);
    stage.add(shapesLayer);
    
    rover.show_camera_controls = function () {
        console.log('show_camera_controls start');
        camera_circle.setStroke('green');
        horz_line.setStroke('orange');
        vert_line.setStroke('orange');
        knob.setDragBoundFunc(camera_bound);
        stage.draw();
        console.log('show_camera_controls end');
    };
    rover.show_movement_controls = function () {
        console.log('show_movement_controls start');
        camera_circle.setStroke('white');
        horz_line.setStroke('green');
        vert_line.setStroke('green');
        knob.setDragBoundFunc(movement_bound);
        reset_stage();
        console.log('show_movement_controls end');
    };
    rover.set_camera_pos_h = function (horz) {
        x = start_x + (90-horz)*max_camera/90;
        console.log('x->'+x);
        knob.setX(x);
        rover.camh = horz;
        stage.draw();
    };
    rover.set_camera_pos_v = function (vert) {
        y = start_y + (vert-90)*max_camera/90;
        console.log('y->'+y);
        knob.setY(y);
        rover.camv = vert;
        stage.draw();
    };
}

function hide_pad() {
    document.getElementById('control_area').style.display = 'none';
}
function show_pad() {
    document.getElementById('control_area').style.display = '';
}
function hide_sliders() {
    document.getElementById('control_area_slider').style.display = 'none';
}
function show_sliders() {
    document.getElementById('control_area_slider').style.display = '';
}
function hide_spectrum() {
    document.getElementById('spectrum_measurements').style.display = 'none';
}
function show_spectrum() {
    document.getElementById('spectrum_measurements').style.display = '';
}
function hide_history() {
	hide_spec_chart();
	hide_humidity_chart();
	hide_solar_chart();
	hide_temp_chart();
	document.getElementById('histories').style.display = 'none';
}
function show_history() {
	document.getElementById('histories').style.display = '';
}

function hide_spec_chart() {
	document.getElementById('spec_chart').style.display = 'none';
}
function show_spec_chart() {
	document.getElementById('spec_chart').style.display = '';
}
function hide_humidity_chart() {
	document.getElementById('humidity_chart').style.display = 'none';
}
function show_humidity_chart() {
	document.getElementById('humidity_chart').style.display = '';
}
function hide_temp_chart() {
	document.getElementById('temp_chart').style.display = 'none';
}
function show_temp_chart() {
	document.getElementById('temp_chart').style.display = '';
}
function hide_solar_chart() {
	document.getElementById('solar_chart').style.display = 'none';
}
function show_solar_chart() {
	document.getElementById('solar_chart').style.display = '';
}

function open_spec_chart() {
	hide_solar_chart();
	hide_temp_chart();
	hide_humidity_chart();
	show_spec_chart();
	draw_spec_history();
}
function open_solar_chart() {
	hide_spec_chart();
	hide_temp_chart();
	hide_humidity_chart();
	show_solar_chart();
	draw_solar_history();
}
function open_temp_chart() {
	hide_solar_chart();
	hide_spec_chart();
	hide_humidity_chart();
	show_temp_chart();
	draw_temperature_history();
}
function open_humidity_chart() {
	hide_solar_chart();
	hide_temp_chart();
	hide_spec_chart();
	show_humidity_chart();
	draw_humidity_history();
}

function open_pad() {
	hide_history();
	hide_sliders();
	hide_spectrum();
	show_pad();
}
function open_spectrum() {
	hide_history();
	hide_sliders();
	hide_pad();
	show_spectrum();
}
function open_sliders() {
	hide_history();
	hide_pad();
	hide_spectrum();
	show_sliders();
}
function open_history() {
	hide_pad();
	hide_spectrum();
	hide_sliders();
	show_history();
	open_temp_chart();
}

function switch_controls() {
	if(document.getElementById('control_area').style.display == '') {
		open_sliders();
	} else {
		open_pad();
	}
}

function handler_text(params) {
    var code = params[0];
    var text = params[1];
    var msgclass;
    switch (code) {
        case 'connected':
            msgclass = 'good';
            var video = document.getElementById('video1');
            video.src = "http://"+address+":"+port+"/video";
            break;
        case 'connection lost':
        case 'protocol error':
            msgclass = 'bad';
            break;
        case 'connection failed':
            msgclass = 'note';
            break;
        case 'chosen':
            msgclass = 'info';
            show_big_message(text);
            show_pad();
			enable_buttons();
			setTimeout(measureHumidity,5000);
			setTimeout(measureTemperature,5000);
			rover.control = true;
            break;
        case 'not chosen':
            msgclass = 'info';
			rover.control = false;
            show_big_message(text);
            hide_pad();
			disable_all_buttons_but_history();
            break;
    }
    add_log(text, msgclass);
}

function handler_mars(params) {
    var code = params[0];
    var value = params[1];
	//console.log("received code: "+code);
    switch (code) {
		case 'R': // spectrum r
            //var spec_data = document.getElementById('sensor_spec_r');
            //var data = spec_data.innerHTML.split(',');
            //data[0] = value;
            //spec_data.innerHTML = data[0]+','+data[1]+','+data[2]+','+data[3];
			//spec_data.innerHTML = value;
			append_spectrum(value, SR);
			break;
		case 'G': // spectrum g
            //var spec_data = document.getElementById('sensor_spec_g');
            //var data = spec_data.innerHTML.split(',');
            //data[1] = value;
            //spec_data.innerHTML = data[0]+','+data[1]+','+data[2]+','+data[3];
            //spec_data.innerHTML = value;
			append_spectrum(value, SG);
			break;
		case 'B': // spectrum b
            //var spec_data = document.getElementById('sensor_spec_b');
            //var data = spec_data.innerHTML.split(',');
            //data[2] = value;
            //spec_data.innerHTML = data[0]+','+data[1]+','+data[2]+','+data[3];
            //spec_data.innerHTML = value;
			append_spectrum(value, SB);
			break;
		case 'IR': // spectrum ir
            //var spec_data = document.getElementById('sensor_spec_ir');
            //var data = spec_data.innerHTML.split(',');
            //data[3] = value;
            //spec_data.innerHTML = data[0]+','+data[1]+','+data[2]+','+data[3];
            //spec_data.innerHTML = value;
			append_spectrum(value, SIR);
			break;
        case 'AX': // accelerometer x
            //var acc_data = document.getElementById('sensor_acc_data');
            //var data = acc_data.innerHTML.split(',');
            //data[0] = value;
            //acc_data.innerHTML = data[0]+','+data[1]+','+data[2];
			received_acc_x(value);
            break;
        case 'AY': // accelerometer y
            //var acc_data = document.getElementById('sensor_acc_data');
            //var data = acc_data.innerHTML.split(',');
            //data[1] = value;
            //acc_data.innerHTML = data[0]+','+data[1]+','+data[2];
			received_acc_y(value);
            break;
        case 'AZ': // accelerometer z
            //var acc_data = document.getElementById('sensor_acc_data');
            //var data = acc_data.innerHTML.split(',');
            //data[2] = value;
            //acc_data.innerHTML = data[0]+','+data[1]+','+data[2];
			received_acc_z(value);
            break;
        case 'MX': // magnetic x
            //var mag_data = document.getElementById('sensor_mag_data');
            //var data = mag_data.innerHTML.split(',');
            //data[0] = value;
            //mag_data.innerHTML = data[0]+','+data[1]+','+data[2];
			received_compass_x(value);
            break;
        case 'MY': // magnetic y
           // var mag_data = document.getElementById('sensor_mag_data');
            //var data = mag_data.innerHTML.split(',');
            //data[1] = value;
            //mag_data.innerHTML = data[0]+','+data[1]+','+data[2];
			received_compass_y(value);
            break;
        case 'MZ': // magnetic z
            //var mag_data = document.getElementById('sensor_mag_data');
            //var data = mag_data.innerHTML.split(',');
            //data[2] = value;
            //mag_data.innerHTML = data[0]+','+data[1]+','+data[2];
			received_compass_z(value);
            break;
		case 'HU': // humidity
            var hum_data = document.getElementById('sensor_hum_data');
            hum_data.innerHTML = value;
			append_humidity(value);
            break;
		case 'TE': // temperature
            var temp_data = document.getElementById('sensor_temp_data');
            temp_data.innerHTML = value;
			append_temperature(value);
            break;
		case 'AU': // solar panel
            var solar_data = document.getElementById('sensor_solar_data');
            value = Math.round((1023-value)/10.24);
            solar_data.innerHTML = value;
			append_solar(value);
            break;
        case 'H': // camera horizontal
            console.log('H:'+value);
            rover.set_camera_pos_h(value);
            break;
        case 'P': // camera vertical
            console.log('P:'+value);
            rover.set_camera_pos_v(value);
            break;
        default:
            console.log('Unknown message: "'+code+':'+value+'"');
            break;
    }
}

function handler_server(params) {
    var code = params[0];
    var value = params[1];
    switch (code) {
        case 'spectrometer_calibration': // calibration data
			console.log("received spectrometer calibration data.. bujaa!");
            var spectrum = value.split(',');
			rover.spec_blue = 1*spectrum[0];
			rover.spec_green = 1*spectrum[1];
			rover.spec_red = 1*spectrum[2];
			rover.spec_ir = 1*spectrum[3];
			rover.spec_calibrated = true;
            break;
        case 'ping':
			mars.send('pong:'+value);
			break;
        case 'pingtime':
        	var latency = document.getElementById('latency');
        	latency.innerHTML = value;
    }
}

function add_log(text, msgclass) {
    function pad(num) {
        if (num < 10) return '0'+num;
        return ''+num;
    }
    var now = new Date();
    var h = now.getHours(), m = now.getMinutes(), s = now.getSeconds();
    var logtext = '['+pad(h)+':'+pad(m)+':'+pad(s)+'] '+text;
    var loglist = document.getElementById('loglist');
    var listnode = document.createElement('li');
    listnode.innerHTML = logtext;
    listnode.className = msgclass;
    loglist.appendChild(listnode);
	loglist.parentNode.scrollByLines(1);
}

function show_big_message(text) {
    var bigmsgbox = document.getElementById('bigmsg');
    bigmsgbox.innerHTML = text;
    bigmsg.style.visibility = 'visible'
    bigmsg.style.opacity = 1;
    setTimeout(function (){
        bigmsgbox.style.opacity = 0;
    }, 3000);
    setTimeout(function (){
        bigmsgbox.style.visibility = 'hidden';
        bigmsgbox.innerHTML = '';
    }, 4000);
}

function setLanguage(langid) {
    interface_language = langid;
    mars.send('set:language:'+langid);
    if (langid == 'fi') {
        document.getElementById('title').innerHTML = "LUMATech Mönkijä - Ohjauspaneeli";
        
        document.getElementById('latency_title').innerHTML = "Viive: ";
		
		//document.getElementById('switch').innerHTML = "Ohjaus";
        document.getElementById('cambutton').innerHTML = "Kameran ohjaus";
        document.getElementById('camreset').innerHTML = "Kamera keskelle";
		//document.getElementById('spectrum_but').innerHTML = "Mittaa spektri";
		document.getElementById('temperature_but').innerHTML = "Mittaa lämpötila ja kosteus";
		document.getElementById('history_but').innerHTML = "Sensorien historiat";
		
		document.getElementById('sensor_hum_name').innerHTML = "Kosteus";
		document.getElementById('sensor_temp_name').innerHTML = "Lämpötila";
		document.getElementById('sensor_solar_name').innerHTML = "Valoisuus";
		
		document.getElementById('add_button').innerHTML = "Lisää";
		document.getElementById('duration').innerHTML = "Kesto";
		document.getElementById('speed').innerHTML = "Nopeus";
		document.getElementById('del_button').innerHTML = "Poista";
		document.getElementById('ex_button').innerHTML = "Aja";
		
		document.getElementById('spectrum_title').innerHTML = "Spektrin mittaaminen";
		document.getElementById('history_title').innerHTML = "Sensorien historiat";
		document.getElementById('history_help').innerHTML = "Valitse tarkasteltava sensori";
		
		//document.getElementById('spec_history_but').innerHTML = "Spektri";
		document.getElementById('hum_history_but').innerHTML = "Kosteus";
		document.getElementById('temp_history_but').innerHTML = "Lämpötila";
		document.getElementById('sol_history_but').innerHTML = "Valoisuus";
    }
    else {
		document.getElementById('title').innerHTML = "LUMATech Rover - Control panel";
		
		document.getElementById('latency_title').innerHTML = "Latency: ";
		
		//document.getElementById('switch').innerHTML = "Controls";
        document.getElementById('cambutton').innerHTML = "Control camera";
        document.getElementById('camreset').innerHTML = "Center camera";
		//document.getElementById('spectrum_but').innerHTML = "Measure spectrum";
		document.getElementById('temperature_but').innerHTML = "Get temp. and hum.";
		document.getElementById('history_but').innerHTML = "Histories";
		
		document.getElementById('sensor_hum_name').innerHTML = "Humidity";
		document.getElementById('sensor_temp_name').innerHTML = "Temperat.";
		document.getElementById('sensor_solar_name').innerHTML = "Solar";
		
		document.getElementById('add_button').innerHTML = "Add cmd";
		document.getElementById('duration').innerHTML = "Duration";
		document.getElementById('speed').innerHTML = "Speed";
		document.getElementById('del_button').innerHTML = "Del";
		document.getElementById('ex_button').innerHTML = "Exec";
		
		document.getElementById('spectrum_title').innerHTML = "Measuring spectrum";
		document.getElementById('history_title').innerHTML = "Sensor histories";
		document.getElementById('history_help').innerHTML = "Select a sensor";
		
		//document.getElementById('spec_history_but').innerHTML = "Spectrum";
		document.getElementById('hum_history_but').innerHTML = "Humidity";
		document.getElementById('temp_history_but').innerHTML = "Temperature";
		document.getElementById('sol_history_but').innerHTML = "Solar";
    }
}

function switch_control() {
    // switch control between camera and movement
	open_pad();
    if (rover.camera) {
        // switch back to movement
        document.getElementById('control_pad').style.background = 'white';
        document.getElementById('cambutton').style.background = '';
        rover.detachCamera();
        rover.show_movement_controls();
    }
    else {
        // switch to camera control
        document.getElementById('control_pad').style.background = 'orange';
        document.getElementById('cambutton').style.background = 'blue';
        rover.set_camera_pos_h(rover.camh);
        rover.set_camera_pos_v(rover.camv);
        rover.askCameraPosition();
        rover.attachCamera();
        rover.show_camera_controls();
    }
}

function reset_camera() {
    // reset camera position
    var move_cam = true;
    if (!rover.camera) {
        move_cam = false;
        rover.attachCamera(false);
        setTimeout(function () {
            if (!rover.camera) rover.detachCamera();
        }, 1000);
    }
    rover.setCameraH(90);
    rover.setCameraV(90);
    if (move_cam) {
        rover.set_camera_pos_h(90);
        rover.set_camera_pos_v(90);
    }
}
function append_humidity(value) {
	humidity.shift();
	humidity.push(value);
	document.getElementById('sensor_hum_data').innerHTML = value;
}
function append_temperature(value) {
	temperature.shift();
	temperature.push(value);
	document.getElementById('sensor_temp_data').innerHTML = value;
}
function append_solar(value) {
	solar.shift();
	solar.push(value);
	document.getElementById('sensor_solar_data').innerHTML = value;
}

function append_spectrum(value, spec) {
	 switch (spec) {
		case SR:
			if(spec_red_counter < 5) {
				spec_red_tmp[spec_red_counter] = value;
				spec_red_counter++;
			}
			break;
		case SG:
			if(spec_green_counter < 5) {
				spec_green_tmp[spec_green_counter] = value;
				spec_green_counter++;
			}
			break;
		case SB:
			if(spec_blue_counter < 5) {
				spec_blue_tmp[spec_blue_counter] = value;
				spec_blue_counter++;
			}
			break;
		case SIR:
			if(spec_ir_counter < 5) {
				spec_ir_tmp[spec_ir_counter] = value;
				spec_ir_counter++;
			}
			break;
	}
	
	if(spec_red_counter >= 5 &&
		spec_blue_counter >= 5 &&
		spec_green_counter >= 5 &&
		spec_ir_counter >= 5) {
		
		var spec_red_sum = 0;
		var spec_blue_sum = 0;
		var spec_green_sum = 0;
		var spec_ir_sum = 0;
		var i;
		
		for(i = 0; i < 5; i++) spec_red_sum += 1*spec_red_tmp[i];
		for(i = 0; i < 5; i++) spec_blue_sum += 1*spec_blue_tmp[i];
		for(i = 0; i < 5; i++) spec_green_sum += 1*spec_green_tmp[i];
		for(i = 0; i < 5; i++) spec_ir_sum += 1*spec_ir_tmp[i];
		
		spec_red_sum = spec_red_sum/5;
		spec_blue_sum = spec_blue_sum/5;
		spec_green_sum = spec_green_sum/5;
		spec_ir_sum = spec_ir_sum/5;
		
		spec_red_sum = spec_red_sum/rover.spec_red;
		spec_blue_sum = spec_blue_sum/rover.spec_blue;
		spec_green_sum = spec_green_sum/rover.spec_green;
		spec_ir_sum = spec_ir_sum/rover.spec_ir;
		
		spec_red_sum = spec_red_sum.toFixed(4);
		spec_blue_sum = spec_blue_sum.toFixed(4);
		spec_green_sum = spec_green_sum.toFixed(4);
		spec_ir_sum = spec_ir_sum.toFixed(4);
		
		save_spectrum(spec_red_sum, SR);
		save_spectrum(spec_green_sum, SG);
		save_spectrum(spec_blue_sum, SB);
		save_spectrum(spec_ir_sum, SIR);
		
		draw_spec_diagram();
		spec_red_counter = 0;
		spec_blue_counter = 0;
		spec_green_counter = 0;
		spec_ir_counter = 0;
		enable_buttons();
	}
}

function save_spectrum(value, spec) {
	 switch (spec) {
		case SR:
			spec_red.shift();
			spec_red.push(value);
			document.getElementById('sensor_spec_r').innerHTML = value;
			break;
		case SG:
			spec_green.shift();
			spec_green.push(value);
			document.getElementById('sensor_spec_g').innerHTML = value;
			break;
		case SB:
			spec_blue.shift();
			spec_blue.push(value);
			document.getElementById('sensor_spec_b').innerHTML = value;
			break;
		case SIR:
			spec_ir.shift();
			spec_ir.push(value);
			document.getElementById('sensor_spec_ir').innerHTML = value;
			break;
	}
}
var plot1;
var plot2;
var plot3;
var plot4;
var plot5;
function draw_spec_diagram() {
	console.log("drawing spec diagram");
	console.log(spec_red);
	console.log(spec_green);
	console.log(spec_blue);
	console.log(spec_ir);
	
	if(interface_language == 'fi') {
		document.getElementById('spectrum_results').innerHTML = "Mittaukset suoritettu!";
	} else {
		document.getElementById('spectrum_results').innerHTML = "Measuring ready!";
	}
	
	document.getElementById('chart1').innerHTML = null;
	
	var line1 = [14, 32, 41, 44, 40];
  plot1 = $.jqplot('chart1', [[spec_blue[9]], [spec_green[9]], [spec_red[9]],[spec_ir[9]]], { //spec_green[9],spec_red[9],spec_ir[9]]
    title: 'Bar Chart with Point Labels', 
    seriesDefaults: {renderer: $.jqplot.BarRenderer},
    series: [ 
		{color:"4242ae", pointLabels:{show: true, labels:['B']}}, 
		{color:"3fb13f", pointLabels:{show: true, labels:['G']}},
		{color:"b33a3a", pointLabels:{show: true, labels:['R']}},
		{color:"ac41ab", pointLabels:{show: true, labels:['IR']}}
		], // seriesColors: [ "4242ae", "3fb13f", "b33a3a", "ac41ab"],
    axes: {
      xaxis:{renderer:$.jqplot.CategoryAxisRenderer},
      yaxis:{padMax:1.3, min: 0, max: 1.3}}
  });

	/*
	plot1 = $.jqplot ('chart1', [spec_red, spec_green, spec_blue, spec_ir],{
      title: 'Spectrum history',
      axesDefaults: {
        labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
        xaxis: {
          label: "",
          pad: 0
        },
        yaxis: {
          label: "Values"
        }
      },
	  seriesColors: [ "b33a3a", "3fb13f", "4242ae", "ac41ab"],
	  series:[ 
          {
			markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          },
          { 
            markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          }
      ]
    });
	*/
}
function draw_spec_history() {
	console.log("drawing spec history");
	console.log(spec_red);
	console.log(spec_green);
	console.log(spec_blue);
	console.log(spec_ir);
	document.getElementById('spec_chart').innerHTML = null;
	plot2 = $.jqplot ('spec_chart', [spec_red, spec_green, spec_blue, spec_ir],{
      title: 'Spectrum history',
      axesDefaults: {
        labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
        xaxis: {
          label: "",
          pad: 0
        },
        yaxis: {
          label: "Values",
		  max: 1.3
        }
      },
	  seriesColors: [ "b33a3a", "3fb13f", "4242ae", "ac41ab"],
	  series:[ 
          {
			markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          },
          { 
            markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          }
      ]
    });
}

function draw_humidity_history() {
	console.log("drawing humidity history");
	console.log(humidity);
	document.getElementById('humidity_chart').innerHTML = null;
	plot3 = $.jqplot ('humidity_chart', [humidity],{
      title: 'Humidity history',
      axesDefaults: {
        labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
        xaxis: {
          label: "",
          pad: 0
        },
        yaxis: {
          label: "Values",
		  max: 100
        }
      },
	  seriesColors: ["4242ae"],
	  series:[ 
          { 
			markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          },
          { 
            markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          }
      ]
    });
}

function draw_temperature_history() {
	console.log("drawing temperature history");
	console.log(temperature);
	document.getElementById('temp_chart').innerHTML = null;
	plot3 = $.jqplot ('temp_chart', [temperature],{
      title: 'Temperature history',
      axesDefaults: {
        labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
        xaxis: {
          label: "",
          pad: 0
        },
        yaxis: {
          label: "Values",
		  max: 100
        }
      },
	  seriesColors: ["b33a3a"],
	  series:[ 
          { 
			markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          },
          { 
            markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          }
      ]
    });
}

function draw_solar_history() {
	console.log("drawing solar history");
	console.log(solar);
	document.getElementById('solar_chart').innerHTML = null;
	plot3 = $.jqplot ('solar_chart', [solar],{
      title: 'Solar history',
      axesDefaults: {
        labelRenderer: $.jqplot.CanvasAxisLabelRenderer
      },
      axes: {
        xaxis: {
          label: "",
          pad: 0
        },
        yaxis: {
          label: "Values",
		  max: 1024
        }
      },
	  seriesColors: ["d09a32"],
	  series:[ 
          { 
			markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          },
          { 
            markerOptions: { style:"circle" }
          }, 
          {
            markerOptions: { style:"circle" }
          }
      ]
    });
}

function measure_spectrum() {
	console.log("measuring spectrum");
	if(rover.spec_calibrated) {
		open_spectrum();
		console.log("measuring spectrum");
		document.getElementById('chart1').innerHTML = null;
		if(interface_language == 'fi') {
			document.getElementById('spectrum_results').innerHTML = "Mitataan spektriä..";
		} else {
			document.getElementById('spectrum_results').innerHTML = "Measuring spectrum..";
		}
		disable_buttons();
		rover.measureSpectrum();
	} else {
		if(interface_language == 'fi') {
			document.getElementById('spectrum_results').innerHTML = "<div style='color:red;'>Spektrometrin kalibraatiodata puuttuu!</div>";
		} else {
			document.getElementById('spectrum_results').innerHTML = "<div style='color:red;'>Missing calibration data for spectrometer!</div>";
		}
	}
}

function show_results() {
	document.getElementById('spectrum_results').innerHTML = "done!";
	enable_buttons();
}

function add_command(new_cmd) {
	if(commands.length < 5) {
		console.log("adding command");
		console.log(new_cmd);
		commands[commands.length] = new_cmd;
		console.log(commands[commands.length-1]);
		draw_commands();
	} else {
		console.log("too many commands: " + commands.length);
	}
}

function delete_command() {
	commands.pop();
	draw_commands();
}

function draw_commands() {
	console.log("drawing commands");
	console.log(commands);
	for(var i = 0; i < commands.length; i++) {
		if(commands[i] === undefined) {
			console.log(document.getElementById('cmd'+(i+1)) + " is null");
			document.getElementById('cmd'+(i+1)).innerHTML = "rdy";
			document.getElementById('cmd'+(i+1)).style.background = "";
		} else {
			console.log(document.getElementById('cmd'+(i+1)));
			document.getElementById('cmd'+(i+1)).title = "dir: " + commands[i].moving + " - speed: " + commands[i].speed + " - dur: " + commands[i].duration;
			document.getElementById('cmd'+(i+1)).innerHTML = commands[i].moving;
			document.getElementById('cmd'+(i+1)).style.background = "#4242ae";
		}
	}
	for(var j = commands.length+1; j < 6; j++) {
		console.log(j);
		document.getElementById('cmd'+j).innerHTML = "#"+j;
		document.getElementById('cmd'+j).style.background = "";
	}
}

function getCheckedRadioId(name) {
    var elements = document.getElementsByName(name);

    for (var i= 0; i < elements.length; i++)
        if (elements[i].checked) return elements[i].value;
}

function execute_commands() {
	if(commands.length > 0) {
		var timeout = 0;
		disable_buttons();
		for(var i = 0; i < commands.length; i++) {
			console.log(timeout);
			if(commands[i].moving == "fwd") {
				setTimeout(drive, parseInt(timeout), commands[i].speed);
			} else if(commands[i].moving == "bwd") {
				setTimeout(drive, parseInt(timeout), -(commands[i].speed));
			} else if(commands[i].moving == "right") {
				setTimeout(turn, parseInt(timeout), commands[i].speed);
			} else if(commands[i].moving == "left") {
				setTimeout(turn, parseInt(timeout), -(commands[i].speed));
			} else if(commands[i].moving == "stop") {
				setTimeout(stop_motors, parseInt(timeout));
			}
			timeout = timeout + parseInt(commands[i].duration);
			console.log(timeout);
			//setTimeout(function() {console.log("nullifying "+i); commands.splice(i-1, 1, undefined); draw_commands();}, parseInt(timeout));
			setTimeout(stop_motors, parseInt(timeout));
			timeout = timeout + 1000;
			
		}
		setTimeout(enable_buttons, timeout);
		setTimeout(function() { commands = new Array(); draw_commands();}, timeout);
		//commands = new Array();
		//draw_commands();
	}
}
function stop_motors() {
	console.log("stopped motors");
	rover.moving = NOT_MOVING;
	for(var i = 0; commands.length; i++) {
		if(commands[i] !== undefined) {
			commands.splice(i, 1, undefined);
			break;
		}
	}
	rover.setSpeed(0);
	draw_commands();
}

function drive(speed) {
	rover.moving = MOVING_DRIVE;
	console.log("driving: "+speed);
	rover.setSpeed(speed);
}

function turn(speed) {
	rover.moving = MOVING_TURN;
	console.log("turning: "+speed);
	rover.setSpeed(speed);
}

function measureTemperature() {
	if(rover.control) {
		rover.measureTemperature();
		//if(drawing_temperature) draw_temperature_history();
		//setTimeout(measureTemperature,5000);
	}
}

function measureHumidity() {
	if(rover.control) {
		rover.measureHumidity();
		//if(drawing_humidity) draw_humidity_history();
		//setTimeout(measureHumidity,5000);
	}
}

var results = false;
var count = 1;
var tc = 0;
function test_results() {
	var first_v = Math.floor((Math.random()*1000)+1);
	var second_v = Math.floor((Math.random()*1000)+1);
	var first_d = Math.random();
	var second_d = Math.random();
	console.log(first_d);
	if(first_d > 0.5) first_v = -(first_v);
	if(second_d > 0.5) second_v = -(second_v);
	received_compass_x(first_v);
	received_compass_y(second_v);
}
function indicate_measuring() {
	tc++;
	if(tc > 80) {
		results = true;
	}
	if(tc%3 == 0) {
		document.getElementById('spectrum_results').innerHTML = "Running measurements...done";
		var r = Math.floor((Math.random()*10)+1);
		var g = Math.floor((Math.random()*10)+1);
		var b = Math.floor((Math.random()*10)+1);
		var ir = Math.floor((Math.random()*10)+1);
		append_spectrum(r, SR);
		append_spectrum(g, SG);
		append_spectrum(b, SB);
		append_spectrum(ir, SIR);
		setTimeout(draw_spec_diagram, 100);
	}if(!results) {
		if(count > 3) {
			count = 1;
			document.getElementById('spectrum_results').innerHTML = "Running measurements";
		} else {
			count++;
			document.getElementById('spectrum_results').innerHTML = document.getElementById('spectrum_results').innerHTML + ".";
		}
		setTimeout(indicate_measuring,1000);
	} else {
		
		
		//document.getElementById('sensor_spec_r').innerHTML = 252;
		//document.getElementById('sensor_spec_g').innerHTML = 892;
		//document.getElementById('sensor_spec_b').innerHTML = 234;
		//document.getElementById('sensor_spec_ir').innerHTML = 297;
		
		enable_buttons();
	}
}

function init_compass() {
    var canvas = document.getElementById('compass');
 
    if(canvas.getContext('2d')) {
        ctx1 = canvas.getContext('2d');

        needle = new Image();
        needle.src = 'arrow.png';

        img = new Image();
        img.src = 'compass.png';
        img.onload = imgLoaded;
    } else {
        alert("Canvas not supported!");
    }
}

function imgLoaded() {
    setTimeout(process_compass, 0, 0, 0);
}
function convert_cz(value) {
	var canvas = document.getElementById('compass');
	var height = canvas.height;
	var divider = 1024/((height-40)/2);
	return value/divider;
}

function draw_compass(degrees, z) {
	ctx1.clearRect(0, 0, 140, 100);
	
	var canvas = document.getElementById('compass');
	var height = canvas.height;
	
	ctx1.strokeStyle="#888";
	ctx1.lineWidth = 5;
	ctx1.beginPath();
	ctx1.moveTo(120, 10);
	ctx1.lineTo(120, 90);
	ctx1.stroke();
	ctx1.lineWidth = 3;
	calculate_arrow(120, 50, 120, 10, 10, ctx1);
	calculate_arrow(120, 50, 120, 90, 10, ctx1);
	
	ctx1.strokeStyle="#333";
	ctx1.lineWidth = 1;
	ctx1.beginPath();
	ctx1.moveTo(120, 15);
	ctx1.lineTo(120, 85);
	ctx1.stroke();
	//ctx1.lineWidth = 1;
	//calculate_arrow(120, 50, 120, 10, 10);
	//calculate_arrow(120, 50, 120, 90, 10);
	
	ctx1.strokeStyle="black";
	ctx1.font = "8pt Arial";
	ctx1.strokeText("z", 110, 95);
	
	ctx1.strokeStyle="#666";
	ctx1.lineWidth = 2;
	ctx1.beginPath();
	ctx1.moveTo(115, height/2);
	ctx1.lineTo(125, height/2);
	ctx1.stroke();
	
	ctx1.beginPath();
	ctx1.strokeStyle="#333";
	ctx1.arc(120, 50-convert_cz(z), 5,0, 2*Math.PI);
	ctx1.fillStyle="red";
	ctx1.fill();
	ctx1.stroke();
	
    ctx1.drawImage(img, 0, 0);
    ctx1.save();
    ctx1.translate(50, 50);
    ctx1.rotate(degrees * (Math.PI / 180));
    ctx1.drawImage(needle, -50, -50);
	
	
	
    ctx1.restore();
}

var compass_x = 0;
var compass_y = 0;
var compass_z = 0;
function received_compass_x(x) {
	compass_x = x;
	//if(compass_y != 0 & compass_z != 0) process_compass();
}
function received_compass_y(y) {
	compass_y = y;
	//if(compass_x != 0 & compass_z != 0) process_compass();
}
function received_compass_z(z) {
	compass_z = z;
	//if(compass_x != 0 & compass_y != 0) process_compass();
}
function process_compass() {
	//console.log("process compass");
	//console.log(compass_x);
	//console.log(compass_y);
	//console.log(compass_z); 
	if(compass_x != 0 & compass_y != 0 & compass_z != 0) {
		//console.log(compass_y);
		//console.log(compass_x);
		//console.log(compass_z);
		var angle = 180*(Math.atan2(compass_y,compass_x))/3.14;
		//console.log("angle: "+angle);
		//if(angle < 0) angle += 360;
		draw_compass(angle, compass_z);
		compass_x = 0;
		compass_y = 0;
		compass_z = 0;
	}
	setTimeout(process_compass, 200);
}

function calculate_arrow(x1, y1, x2, y2, d, ctx) {
	var angle = Math.PI/8;
	var lineangle = Math.atan2(y2-y1, x2-x1);
	var h = Math.abs(d / Math.cos(angle));
	var angle1 = lineangle+Math.PI+angle;
	var topx = x2+Math.cos(angle1)*h;
	var topy = y2+Math.sin(angle1)*h;
	var angle2 = lineangle+Math.PI-angle;
	var botx = x2+Math.cos(angle2)*h;
	var boty = y2+Math.sin(angle2)*h;
	draw_arrow(ctx,topx,topy,x2,y2,botx,boty);
}


function draw_arrow(ctx2,x0,y0,x1,y1,x2,y2) {
  ctx2.beginPath();
  ctx2.moveTo(x1,y1);
  ctx2.lineTo(x0,y0);
  ctx2.stroke();
  ctx2.beginPath();
  ctx2.moveTo(x1,y1);
  ctx2.lineTo(x2,y2);
  ctx2.stroke();
  ctx2.beginPath();
  ctx2.moveTo(x0,y0);
  ctx2.lineTo(x2,y2);
  ctx2.stroke();
}

function test() {
	//setTimeout(draw_xy_acc, 1000, 2000, 2000);
	
	for(var i = 1; i <= 10; i++) {
		var r1 = Math.random();
		var r2 = Math.random();
		var r3 = Math.random();
		var x = Math.floor((Math.random()*2000)+1);
		var y = Math.floor((Math.random()*2000)+1);
		var z = Math.floor((Math.random()*2000)+1);
		if(r1 > 0.5) x = -x;
		if(r2 > 0.5) y = -y;
		if(r3 > 0.5) z = -z;
		setTimeout(draw_xy_acc, i*1000, x, y);
		setTimeout(draw_zy_acc, i*1000, z, y);
	}
	
}

var acc_x = 0;
var acc_y = 0;
var acc_z = 0;

function received_acc_x(x) {
	acc_x = x;
	//if(acc_y != 0 & acc_z != 0) process_acc();
}
function received_acc_y(y) {
	acc_y = y;
	//if(acc_x != 0 & acc_z != 0) process_acc();
}
function received_acc_z(z) {
	acc_z = z;
	//if(acc_x != 0 & acc_y != 0) process_acc();
}
function convert_av(value) {
	var canvas = document.getElementById('xy_acc');
	var width = canvas.width;
	var divider = 1024/(width/2);
	return value/divider;
}
function process_acc() {
	//console.log("processing acc");
	//console.log(acc_y);
	//	console.log(acc_x);
	//	console.log(acc_z);
	if(acc_x != 0 & acc_y != 0 & acc_z != 0) {
		//console.log("aasdf");
		
		draw_xy_acc(acc_x, acc_y);
		draw_zy_acc(acc_z, acc_y);
		acc_x = 0;
		acc_y = 0;
		acc_z = 0;
	}
	setTimeout(process_acc, 1000);
}

function init_acc() {
	process_acc();
	//setTimeout(draw_xy_acc, 1000, 1000, 1000);
	//setTimeout(draw_zy_acc, 1000, 1000, 1000);
}

function draw_xy_acc(acc_x, acc_y) {
    //ctx.drawImage(img, 0, 0);
	//console.log("drawing acc xy");
	var canvas = document.getElementById('xy_acc');
	ctx3 = canvas.getContext('2d');
	
    var center_x = (canvas.width/2);
	var center_y = (canvas.height/2);
	
	ctx3.clearRect(0, 0, canvas.width, canvas.height);
	
	ctx3.strokeStyle="grey";
	ctx3.lineWidth = 1;
	ctx3.beginPath();
	ctx3.moveTo(0, center_y);
	ctx3.lineTo(canvas.width, center_y);
	ctx3.stroke();
	calculate_arrow(center_x, center_y, canvas.width, center_y, 5, ctx3);
	
	ctx3.beginPath();
	ctx3.moveTo(center_x,0);
	ctx3.lineTo(center_x, canvas.height);
	ctx3.stroke();
	calculate_arrow(center_x, center_y, center_x, 0, 5, ctx3);
	
	//ctx3.strokeStyle="black";
	ctx3.strokeText("x", canvas.width-10, center_y+10);
	ctx3.strokeText("y", center_x-10, 10);
	ctx3.strokeStyle="black";
	ctx3.strokeText("acc x : " + acc_x, 10, canvas.height-30);
	ctx3.strokeText("acc y : " + acc_y, 10, canvas.height-10);
	
	ctx3.beginPath();
	ctx3.lineWidth = 2;
	
	
	var le_x = center_x+convert_av(acc_x);
	var le_y = center_y+convert_av(acc_y);
	ctx3.moveTo(center_x, center_y);
	ctx3.lineTo(le_x, le_y);
	
	ctx3.arc(center_x, center_y, 2,0, 2*Math.PI, false);
	ctx3.stroke();
	
	ctx3.strokeStyle="green";
	ctx3.stroke();
	calculate_arrow(center_x, center_y, le_x, le_y, 8, ctx3);
}

function draw_zy_acc(acc_z, acc_y) {
    //ctx4.drawImage(img, 0, 0);
	//console.log("drawing acc zy");
	var canvas = document.getElementById('zy_acc');
	ctx4 = canvas.getContext('2d');
	
    var center_x = (canvas.width/2);
	var center_y = (canvas.height/2);
	
	ctx4.clearRect(0, 0, canvas.width, canvas.height);
	
	ctx4.strokeStyle="grey";
	ctx4.lineWidth = 1;
	ctx4.beginPath();
	ctx4.moveTo(0, center_y);
	ctx4.lineTo(canvas.width, center_y);
	ctx4.stroke();
	calculate_arrow(center_x, center_y, canvas.width, center_y, 5, ctx4);
	
	ctx4.beginPath();
	ctx4.moveTo(center_x,0);
	ctx4.lineTo(center_x, canvas.height);
	ctx4.stroke();
	calculate_arrow(center_x, center_y, center_x, 0, 5, ctx4);
	
	//ctx4.strokeStyle="black";
	ctx4.strokeText("z", canvas.width-10, center_y+10);
	ctx4.strokeText("y", center_x-10, 10);
	ctx4.strokeStyle="black";
	ctx4.strokeText("acc z : " + acc_z, 10, canvas.height-30);
	ctx4.strokeText("acc y : " + acc_y, 10, canvas.height-10);
	
	ctx4.beginPath();
	ctx4.lineWidth = 2;
	
	
	var le_x = center_x+convert_av(acc_z);
	var le_y = center_y+convert_av(acc_y);
	ctx4.moveTo(center_x, center_y);
	ctx4.lineTo(le_x, le_y);
	
	ctx4.arc(center_x, center_y, 2,0, 2*Math.PI, false);
	ctx4.stroke();
	
	ctx4.strokeStyle="green";
	ctx4.stroke();
	calculate_arrow(center_x, center_y, le_x, le_y, 8, ctx4);
}

function disable_all_buttons_but_history(){
	//document.getElementById('switch').disabled = true;
	document.getElementById('cambutton').disabled = true;
	document.getElementById('camreset').disabled = true;
	//document.getElementById('spectrum_but').disabled = true;
	document.getElementById('del_button').disabled = true;
	document.getElementById('add_button').disabled = true;
	document.getElementById('ex_button').disabled = true;
	document.getElementById('temperature_but').disabled = true;
	console.log("buttons disabled");
}

function disable_buttons() {
	//document.getElementById('switch').disabled = true;
	document.getElementById('cambutton').disabled = true;
	document.getElementById('camreset').disabled = true;
	//document.getElementById('spectrum_but').disabled = true;
	document.getElementById('history_but').disabled = true;
	document.getElementById('del_button').disabled = true;
	document.getElementById('add_button').disabled = true;
	document.getElementById('ex_button').disabled = true;
	document.getElementById('temperature_but').disabled = true;
	console.log("buttons disabled");
}
function enable_buttons() {
	//document.getElementById('switch').disabled = false;
	document.getElementById('cambutton').disabled = false;
	document.getElementById('camreset').disabled = false;
	//document.getElementById('spectrum_but').disabled = false;
	document.getElementById('history_but').disabled = false;
	document.getElementById('del_button').disabled = false;
	document.getElementById('add_button').disabled = false;
	document.getElementById('ex_button').disabled = false;
	document.getElementById('temperature_but').disabled = false;
	console.log("buttons enabled");
}

function draw_chart() {
 // var plot1 = $.jqplot ('chart1', [[3,7,9,1,4,6,8,2,5]]);
}

function make_connection() {
	console.log("connecting");
    function onopen(ev) {
        if (interface_language == 'fi') {
            add_log('Yhteys muodostettu.', 'good');
        }
        else {
            add_log('Connection established.', 'good');
        }
        setLanguage(interface_language); // set language
        mars.send('control'); // request control
		rover.getSpectrometerCalibration();
		//mars.send('get:spectrometer_calibration');
    }
    function onclose(ev) {
        if (interface_language == 'fi') {
            add_log('Yhteys katkaistu.', 'bad');
        }
        else {
            add_log('Connection closed.', 'bad');
        }
    }
    function onerror(ev) {
        if (interface_language == 'fi') {
            add_log('YhteydessÃ¤ tapahtui virhe.', 'bad');
        }
        else {
            add_log('Error happened in connection.', 'bad');
        }
        mars.close();
    }
    mars = connect_to_mars('ws://'+address+':'+
        port+'/mars',
        onopen, onclose, onerror);
    mars.register_handler('TEXT', handler_text);
    mars.register_handler('mars', handler_mars);
	mars.register_handler('server', handler_server);
}

function initialize(ev) {
    // Initialization routines
    create_pad(); // Create the directional control pad
    open_pad(); // Hide the pad by default
	setTimeout(init_compass,500);
	setTimeout(init_acc,1000);
	//init_compass();
	//init_acc();
    setTimeout(make_connection,1500);
	//make_connection(); // Make connection with the server
	//setTimeout(measureHumidity,5000);
	//setTimeout(measureTemperature,5000);
	//test();
}

document.addEventListener('DOMContentLoaded', initialize, false);

